//
//  MDHSegmentedControlController.m
//  MDHPT
//
//  Created by 高得华 on 2019/6/6.
//  Copyright © 2019年 高得华. All rights reserved.
//

#import "MDHSegmentedControlController.h"
#import "MDHFileConstant.h"

#if __has_include("MDHPT/MDHPT-Swift.h")
#import "MDHPT/MDHPT-Swift.h"
#else
#import "MDHPT-Swift.h"
#endif

@interface MDHSegmentedControlController ()

///ViewModel
@property (nonatomic, strong, readwrite) MDHSegmentedControlViewModel * viewModel;

@end

@implementation MDHSegmentedControlController

@synthesize viewModel = _viewModel;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.categoryView.delegate = self;
    
    self.pagerView = [self preferredPagingView];
    self.pagerView.mainTableView.gestureDelegate = self;
    [self.view addSubview:self.pagerView];
    self.categoryView.contentScrollView = self.pagerView.listContainerView.collectionView;
    //导航栏隐藏的情况，处理扣边返回，下面的代码要加上
    if (self.navigationController.interactivePopGestureRecognizer) {
        [self.pagerView.listContainerView.collectionView.panGestureRecognizer requireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
        [self.pagerView.mainTableView.panGestureRecognizer requireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //处于第一个item的时候，才允许屏幕边缘手势返回
    self.navigationController.interactivePopGestureRecognizer.enabled = (self.categoryView.selectedIndex == 0);
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //离开页面的时候，需要恢复屏幕边缘手势，不能影响其他页面
    self.navigationController.interactivePopGestureRecognizer.enabled = true;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if (self.viewModel.isPagerView) {
        CGFloat pvfY = 0;
        CGFloat height1 = self.view.bounds.size.height;//-[self preferredCategoryViewHeight];
        if (self.navigationController.navigationBar.translucent) {
            pvfY = kMMWPTFC().kNavSafeArea;
            height1 -= pvfY;
        }
        if (!self.hidesBottomBarWhenPushed) {
            height1 -= kMMWPTFC().kTabbarSafeArea;
        }else{
            height1 -= kMMWPTFC().kSafeAreaBottom;
        }
        self.pagerView.frame = CGRectMake(0, pvfY, self.view.bounds.size.width, height1);
    }
}

///ViewModel
- (void)bindViewModel {
    [super bindViewModel];
    
    @weakify(self);
    ///监听是否在导航栏上
    [[[self rac_valuesForKeyPath:@"viewModel.isNavSegment" observer:self] deliverOnMainThread] subscribeNext:^(NSNumber *  _Nullable x) {
        @strongify(self);
        //CGFloat lcvY = [self preferredCategoryViewHeight];
        if (x.boolValue) {//导航栏
            self.categoryView.frame = CGRectMake(0, 0, 240, 40);
            self.viewModel.preferredCategoryViewHeight = 0;
            self.navigationItem.titleView = self.categoryView;
        }else{///不在导航栏
            [self.view addSubview:self.categoryView];
            self.categoryView.frame = CGRectMake(0, kMMWPTFC().kNavSafeArea, self.view.bounds.size.width, [self preferredCategoryViewHeight]);
            //lcvY += kMMWPTFC().kNavSafeArea;
        }
        //self.listContainerView.frame = CGRectMake(0, lcvY, self.view.bounds.size.width, self.view.bounds.size.height);
    }];
    
    ///监听指示器的切换
    [[[self rac_valuesForKeyPath:@"viewModel.categoryComponentPosition" observer:self] deliverOnMainThread] subscribeNext:^(NSNumber *  _Nullable x) {
        @strongify(self);
        JXCategoryIndicatorView * componentView = (JXCategoryIndicatorView *)self.categoryView;
        for (JXCategoryIndicatorComponentView * view in componentView.indicators) {
            view.componentPosition = x.integerValue;
        }
        [componentView reloadData];
    }];
    
    /*///监听是哪种视图
    [[[self rac_valuesForKeyPath:@"viewModel.isPagerView" observer:self] deliverOnMainThread] subscribeNext:^(NSNumber *  _Nullable x) {
        @strongify(self);
        if (x.boolValue) {
            self.pagerView = [self preferredPagingView];
            self.pagerView.mainTableView.gestureDelegate = self;
            [self.view addSubview:self.pagerView];
            self.categoryView.contentScrollView = self.pagerView.listContainerView.collectionView;
            //导航栏隐藏的情况，处理扣边返回，下面的代码要加上
            [self.pagerView.listContainerView.collectionView.panGestureRecognizer requireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
            [self.pagerView.mainTableView.panGestureRecognizer requireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
        }else{
        }
    }];*/
}

- (CGFloat)preferredCategoryViewHeight {
    return self.viewModel.preferredCategoryViewHeight;
}

//MARK: - === JXCategoryViewDelegate
///点击选中或者滚动选中都会调用该方法。适用于只关心选中事件，不关心具体是点击还是滚动选中的。
- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index {
    DTLog(@" - ==== -> %@",NSStringFromSelector(_cmd));
    ///侧滑手势处理
    if (self.viewModel.shouldHandleScreenEdgeGesture) {
        self.navigationController.interactivePopGestureRecognizer.enabled = (index == 0);
    }
}
///滚动选中的情况才会调用该方法
- (void)categoryView:(JXCategoryBaseView *)categoryView didScrollSelectedItemAtIndex:(NSInteger)index {
    DTLog(@"%@", NSStringFromSelector(_cmd));
    //[self categoryViewClickScroll:index];
}
///点击选中的情况才会调用该方法
- (void)categoryView:(JXCategoryBaseView *)categoryView didClickSelectedItemAtIndex:(NSInteger)index {
    DTLog(@"%@", NSStringFromSelector(_cmd));
    [self categoryViewClickScroll:index];
}
/*
///正在滚动中的回调
- (void)categoryView:(JXCategoryBaseView *)categoryView scrollingFromLeftIndex:(NSInteger)leftIndex toRightIndex:(NSInteger)rightIndex ratio:(CGFloat)ratio {
}
*/

///更新数据 点击 或者 滑动
- (void)categoryViewClickScroll:(NSInteger)index {
    if (self.viewModel.isPagerView) {
        //请务必实现该方法
        //因为底层触发列表加载是在代理方法：`- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath`回调里面
        //所以，如果当前有5个item，当前在第1个，用于点击了第5个。categoryView默认是通过设置contentOffset.x滚动到指定的位置，这个时候有个问题，就会触发中间2、3、4的cellForItemAtIndexPath方法。
        //如此一来就丧失了延迟加载的功能
        //所以，如果你想规避这样的情况发生，那么务必按照这里的方法处理滚动。
        JXPagerListContainerCollectionView * cv = self.pagerView.listContainerView.collectionView;
        [cv scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:false];
        
        //如果你想相邻的两个item切换时，通过有动画滚动实现。未相邻的两个item直接切换，可以用下面这段代码
        /*
         NSInteger diffIndex = labs(categoryView.selectedIndex - index);
         if (diffIndex > 1) {
         [self.pagerView.listContainerView.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
         }else {
         [self.pagerView.listContainerView.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
         }
         */
    }
}

//MARK: - === 懒加载
- (JXCategoryBaseView *)preferredCategoryView {
    return [[JXCategoryBaseView alloc] init];
}
- (JXCategoryBaseView *)categoryView {
    if (_categoryView == nil) {
        _categoryView = [self preferredCategoryView];
    }
    return _categoryView;
}

///PagingView
- (JXPagerView *)preferredPagingView {
    //return [[JXPagerView alloc] initWithDelegate:self];
    return [[MDHPagerListRefreshView alloc] initWithDelegate:self];
}

//MARK: - = JXPagerMainTableViewGestureDelegate
- (BOOL)mainTableViewGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    //禁止categoryView左右滑动的时候，上下和左右都可以滚动
    if (otherGestureRecognizer == self.categoryView.collectionView.panGestureRecognizer) {
        return NO;
    }
    return [gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] && [otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]];
}

//MARK:  - JXPagerViewDelegate
- (UIView *)tableHeaderViewInPagerView:(JXPagerView *)pagerView {
    return [UIView new];
}
- (NSUInteger)tableHeaderViewHeightInPagerView:(JXPagerView *)pagerView {
    return 0;
}
- (NSUInteger)heightForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return self.viewModel.preferredCategoryViewHeight;
}
- (UIView *)viewForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return self.categoryView;
}
- (NSInteger)numberOfListsInPagerView:(JXPagerView *)pagerView {
    //和categoryView的item数量一致
    return self.viewModel.titles.count;
}
- (id<JXPagerViewListViewDelegate>)pagerView:(JXPagerView *)pagerView initListAtIndex:(NSInteger)index {
    return nil;
}



@end
